/*
 * Created by Wildish on 2016-10-31
 *
 * Contact me with keithknight@qq.com
 *
 * Copyright (c) 2016 Wildish
 */

package com.wildish.hybridframework.jsbinding.webview;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Message;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import com.wildish.hybridframework.core.HybridGlobal;

public class CustomWebChromeClient extends WebChromeClient {

    @Override
    public void onCloseWindow(WebView window) {
        super.onCloseWindow(window);
    }

    @Override
    public boolean onCreateWindow(WebView view, boolean dialog,
                                  boolean userGesture, Message resultMsg) {
        return super.onCreateWindow(view, dialog, userGesture, resultMsg);
    }

    @Override
    public boolean onJsAlert(WebView view, String url, String message,
                             final android.webkit.JsResult result) {
        Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
        result.confirm();
        return true;
    }

    public boolean onJsConfirm(WebView view, String url, String message,
                               final android.webkit.JsResult result) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(
                view.getContext());
        builder.setTitle("Message");
        builder.setMessage(message);
        builder.setPositiveButton(android.R.string.ok,
                new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
        builder.setNeutralButton(android.R.string.cancel,
                new AlertDialog.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                });
        builder.setCancelable(false);
        builder.create();
        builder.show();
        return true;
    }

    /**
     * @param consoleMessage
     * @return
     */
    @Override
    public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
        HybridGlobal.logger.log(consoleMessage.message() + "-- from line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());
        return true;
    }
}
